underworld = {
    depth = tonumber(minetest.settings:get("underworld_depth")) or -25000,
    barrier_size = tonumber(minetest.settings:get("underworld_barrier_size")) or 20,
}

local modpath = minetest.get_modpath("underworld")
dofile(modpath .. "/nodes.lua")
dofile(modpath .. "/portals.lua")
dofile(modpath .. "/mapgen.lua")

-- Miscellaneous
-- Vaporize water in the underworld
minetest.register_abm({
    label = "Vaporize water in underworld",
    nodenames = {"default:water_source", "default:water_flowing", "default:river_water_source", "default:river_water_flowing"},
    interval = 1,
    chance = 1,
    action = function(pos, node)
        if pos.y <= underworld.depth then
            minetest.remove_node(pos)
            minetest.sound_play("default_cool_lava", {pos = pos, max_hear_distance = 16, gain = 0.25})
        end
    end,
})

-- Spawn extra-aggressive dungeon masters in dungeons
if minetest.get_modpath("mobs_monster") then
    mobs:spawn({
        name = "mobs_monster:dungeon_master",
        nodes = {"underworld:brick"},
        min_light = 0,
        max_light = minetest.LIGHT_MAX - 2,
        interval = 10,
        chance = 4,
        active_object_count = 1,
        max_height = underworld.depth,
        on_spawn = function(self, pos)
            self.shoot_interval = 0.5
            self.dogshoot_switch = 0
        end
    })
end

-- Disallow connecting mese portals across the underworld boundary
if minetest.get_modpath("meseportals") then
    local old_can_connect = meseportals.can_connect
    meseportals.can_connect = function(src_portal, dest_portal)
        local src_y = src_portal.pos.y
        local dest_y = dest_portal.pos.y
        if math.min(src_y, dest_y) <= underworld.depth and underworld.depth < math.max(src_y, dest_y) then
            return false, "Mese portals can't connect into or out of the underworld."
        end
        
        return old_can_connect(src_portal, dest_portal)
    end
end